# 导入模块
import re
import random

t = r'python'
txt = 'Hello python,my name is dylan'
txt1 = 'www.hellodylan.cn'
ip = '118.25.4.127'
# 下标从0开始
print(re.search(t, txt))  # <re.Match object; span=(6, 12), match='python'>

# 点号 . 匹配除空格以外的任意字符
print(re.search(r'.', txt))  # <re.Match object; span=(0, 1), match='H'>
print(re.search(r'pyth.', txt))  # <re.Match object; span=(6, 11), match='pytho'>

# \ 仅匹配点号自身
print(re.search(r'\.', txt1))  # <re.Match object; span=(3, 4), match='.'>

# 匹配数字
print(re.search(r'\d', ip))  # <re.Match object; span=(0, 1), match='1'>
print(re.search(r'\d\d', ip))  # <re.Match object; span=(0, 2), match='11'>

# 用[]匹配字符串,默认区分大小写
print(re.search(r'[he]', 'www.hellodylan.cn'))  # <re.Match object; span=(4, 5), match='h'>
print(re.search(r'[k-o]', 'www.hellodylan.cn'))  # <re.Match object; span=(6, 7), match='l'>
print(re.search(r'[2-9]', '7834328'))  # <re.Match object; span=(0, 1), match='7'>
# 匹配 2，3，4，8
print(re.search(r'[2-48]', '7834328'))  # <re.Match object; span=(1, 2), match='8'>

# 用{}限定重复匹配的次数
print(re.search(r'25{3}6', '225556'))  # <re.Match object; span=(1, 6), match='25556'>
print(re.search(r'25{3}6', '2255556'))  # None,次数不匹配
# 设置匹配的次数，用逗号 , 隔开
print(re.search(r'25{2,7}6', '2255556'))  # <re.Match object; span=(1, 7), match='255556'>

# 匹配 0-255的数字
num = str(random.choice(range(256)))
print('num=',num)
# r'[01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5]'
# r'\d{1,2}|1\d\d|2[0-4]|25[0-5]'
# r'[0-5]{1,3}'
exp = r'2[0-4]\d|[01]{0,1}\d{0,1}\d|25[0-5]'
print(re.search(exp,num))

# 匹配ip
ip = str(random.choice(range(1,256)))+'.'+str(random.choice(range(256)))+'.'+str(random.choice(range(256)))+'.'+str(random.choice(range(256)))
print('ip=',ip)
ipExp = r'((2[0-4]\d|[01]{0,1}\d{0,1}\d|25[0-5])\.){3}(2[0-4]\d|[01]{0,1}\d{0,1}\d|25[0-5])'
print(re.search(ipExp,ip))

